package cron

import (
	"bigdevops/src/common"
	"bigdevops/src/pbms"
	"context"
	"fmt"
	"go.uber.org/zap"
	"k8s.io/apimachinery/pkg/util/wait"
	"math/rand"
	"os"
	"runtime"
	"time"
)

func (c *CronManager) InfoReportManager(ctx context.Context) error {

	go wait.UntilWithContext(ctx, c.RunInfoReport, time.Duration(c.Client.Sc.InfoCollectC.RunIntervalSeconds)*time.Second)
	<-ctx.Done()
	c.Client.Sc.Logger.Info("InfoReportManager  收到其他任务退出信号 退出")
	return nil

}

func (c *CronManager) RunInfoReport(ctx context.Context) {

	// https://github.com/shimingyah/pool/blob/master/example/client/main.go
	conn, err := c.Client.Pool.Get()
	if err != nil {
		c.Client.Sc.Logger.Error("[计划任务-信息采集上报]在grpc池中获取连接错误", zap.Error(err))
		return
	}
	defer conn.Close()

	client := pbms.NewInfoReporterClient(conn.Value())

	ctx, cancel := c.Client.GenTwContext()
	defer cancel()
	// 使用这个库 github.com/matishsiao/goInfo 获取linux信息
	nodeInfo := common.GetNodeInfo()
	fmt.Println(nodeInfo)
	sn := nodeInfo.Node.MachineID
	if runtime.GOOS == "windows" {
		sn = "abc"
	}

	// 模拟 disk每次发生变化 增量更新
	frn := func(n int) int {
		rand.Seed(time.Now().UnixNano())
		return rand.Intn(n)
	}
	resp, err := client.AgentInfoReport(ctx, &pbms.AgentInfoReportRequest{
		Hostname:     c.Client.Sc.HostName,
		AgentVersion: common.AGENT_VERSION,
		Ip:           c.Client.Sc.LocalIp,
		Env:          os.Getenv(common.AGENT_VAR_ENV),
		Sn:           sn,
		//Sn:           nodeInfo.Node.MachineID,
		OsType: nodeInfo.OsType,
		OsName: nodeInfo.OS.Name,
		Cpu:    int32(nodeInfo.CPU.Threads),
		Mem:    int32(nodeInfo.Memory.Size),
		Disk:   int32(frn(100)),
	})
	if err != nil {
		c.Client.Sc.Logger.Error("[计划任务-信息采集上报 ]出错", zap.Error(err))
		return
	}
	c.Client.Sc.Logger.Info("[计划任务-信息采集上报 ]服务端返回结果",
		zap.Any("结果", resp),
	)
}
